//
//  SXPhomeViewModel.swift
//  weibo
//
//  Created by shixinPeng on 16/3/1.
//  Copyright © 2016年 shixinPeng. All rights reserved.
//

import UIKit
import AFNetworking
import FMDB

class SXPhomeViewModel: NSObject {
    
    /// 保存微博信息的数组
    lazy var statusesArray:[SXPstatusesViewModel] = [SXPstatusesViewModel]()
    
    ///  获取网络数据
    func loadData(since_id since_id:Int = 0, max_id: Int = 0, FinishClosure:(result:NSInteger) -> (),failes:(error:NSError) -> ()) {
        
        loadCacheStatuse(since_id: since_id, max_id: max_id) { (data: [[String: AnyObject]]) -> () in
            
            
            if data.count > 0 {
                
                for info in data {
                    let infoOBJ = info as! [String : NSObject]
                    
                    let model = SXPstatusModel(Dict: infoOBJ)
                    let statusviewModel = SXPstatusesViewModel()
                    statusviewModel.statusesModel = model
                    
                    self.statusesArray.append(statusviewModel)
                    
                    //self.statusesArray.append(SXPstatusesViewModel(statusesModel: SXPstatusModel(Dict: info)))
                }
                FinishClosure(result: -1)
                
            }else{
                self.loadNetdata(since_id: since_id, max_id: max_id, FinishClosure: FinishClosure,failes:failes)
            }
            
            
        }
        
    }

        
    func loadNetdata(since_id since_id:Int = 0, max_id: Int = 0, FinishClosure:((result:NSInteger) -> ()),failes:((error:NSError) -> Void)) {
            
            //access_token 	true 	string 	采用OAuth授权方式为必填参数，OAuth授权后获得。
            /// 参数
            let params: [String : AnyObject] = ["access_token":SXPuserViewModels.shareInstance.access_token ?? "",
                "max_id":max_id,
                "since_id":since_id]
            //print(params)
            //发送网络请求
            SXPHTTPClient.shareInstance.request(.GET, URLString: "https://api.weibo.com/2/statuses/home_timeline.json", params: params, success: { (JSON) -> () in
                //处理数据
                if let json = JSON {//判空
                    
                    if let statuses = json["statuses"] as? [[String: NSObject]]{
                        //创建一个临时数组
                        var temp = [SXPstatusesViewModel]()
                        //获取所需要的数据
                        for statuse in statuses {
                            //字典转模型
                            let statusesModel = SXPstatusModel(Dict: statuse)
                            
                            //创建微博信息界面模型
                            let statusesViewModel = SXPstatusesViewModel()
                            
                            //添加微博信息界面模型中的数据
                            statusesViewModel.statusesModel = statusesModel
                            
                            //把微博信息界面模型添加到临时数组当中
                            temp.append(statusesViewModel)
                            
                        }
                        if max_id > 0 {//下拉刷新获取数据
                            self.statusesArray = self.statusesArray + temp
                        }else{//第一次数据
                            self.statusesArray = temp + self.statusesArray
                        }
                        
                        //保存数据,把返回的字典数组传入
                        self.saveData(statuses)
                        
                        
                        
                        //利用闭包刷新界面
                        FinishClosure(result: temp.count)
                        
                    }
                }
                }) { (error) -> () in
                  failes(error: error)
            }
        }
        
        
        
        
        //查询数据库数据
         private func loadCacheStatuse(since_id since_id:Int, max_id: Int,finish:(([[String: AnyObject]]) -> ())) {
            //sql语句
            var sql = "SELECT statusId,status FROM t_status \n" +
            "WHERE userId = '\(SXPuserViewModels.shareInstance.userModel!.uid!)'\n"
            //判断是是上拉刷新还是下拉更多
            if since_id > 0 { //下拉刷新
                sql += "AND statusId > \(since_id) \n"
            }else if max_id > 0{//上拉更多
                sql += "AND statusId < \(max_id) \n"
            }
            sql += "ORDER BY statusId DESC LIMIT 20"
            
            printLog("查询数据库数据:sql-->\(sql)")
            
            SXPDbManager.shareManager.queue?.inTransaction({ (db, _) -> Void in
                
                let rs = db.executeQuery(sql, withArgumentsInArray: nil)
                
                var arry = [[String: AnyObject]]()
                
                while rs.next(){
                    
                    let str = rs.stringForColumn("status")
                    
                    //字符串转成二进制,二进制转变为字典
                    let data = str.dataUsingEncoding(NSUTF8StringEncoding)
                    
                    //字典
                    let dic = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0))
                    
                    arry.append(dic as! [String: AnyObject])
                    
                }
                
                finish(arry)
            })
            
            
            
        }
        
        //数据库数据插入
        func saveData(ar: [[String: NSObject]]){
            //sql
            let sql = "INSERT OR REPLACE INTO t_status (statusId,status,userId) VALUES (?,?,?)"
            
            printLog("数据插入sql-->\(sql)")
            //遍历数组,插入数据
            for dic in ar{
                //根据kit获取值
                let statusId = dic["idstr"] as! String
                //ba statue转为二进制文件,在转变为字符串
                let data = try! NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions(rawValue: 0))
                
                let str = NSString(data: data, encoding: NSUTF8StringEncoding)
                
                
                //执行sql
                SXPDbManager.shareManager.queue?.inTransaction({ (db:FMDatabase!, roolback) -> Void in
                    
                    if db.executeUpdate(sql, withArgumentsInArray:  [statusId,str!,SXPuserViewModels.shareInstance.userModel!.uid!]) {
                        
                        
                        printLog("插入成功")
                    }else{
                        printLog("插入失败")
                    }
                    
                    
                    
                })
            }
            
            
            
        }
        
}
